#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H

#include <QObject>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QVariant>
#include <QVariantMap>
#include <QString>
#include <QStringList>
#include <memory>

class DatabaseManager : public QObject
{
    Q_OBJECT

public:
    explicit DatabaseManager(QObject *parent = nullptr);
    ~DatabaseManager();

    // 初始化数据库
    Q_INVOKABLE bool initialize(const QString &databaseName = "app_database.db");
    
    // 检查表是否存在
    Q_INVOKABLE bool tableExists(const QString &tableName);
    
    // 创建表
    Q_INVOKABLE bool createTable(const QString &tableName, const QString &columnsDefinition);
    
    // 插入或更新数据
    Q_INVOKABLE bool insertOrUpdate(const QString &tableName, const QVariantMap &data, const QString &primaryKey = "id");
    
    // 查询数据
    Q_INVOKABLE QVariantMap selectRecord(const QString &tableName, const QVariantMap &conditions);
    
    // 查询多条记录
    Q_INVOKABLE QVariantList selectRecords(const QString &tableName, const QVariantMap &conditions = QVariantMap());
    
    // 删除数据
    Q_INVOKABLE bool deleteRecord(const QString &tableName, const QVariantMap &conditions);
    
    // 根据时间范围查询数据
    Q_INVOKABLE QVariantList selectRecordsByTimestampRange(const QString &tableName, const QString &timestampColumn, const QString &startTimestamp, const QString &endTimestamp);
    
    // 执行自定义SQL查询
    Q_INVOKABLE QVariantList executeQuery(const QString &sql, const QVariantList &bindings = QVariantList());
    
    // 获取最后一次错误信息
    Q_INVOKABLE QString lastError() const;

private:
    std::unique_ptr<QSqlDatabase> m_db;
    QString m_lastError;
    
    QString buildWhereClause(const QVariantMap &conditions);
    bool openDatabase(const QString &databasePath);
};

#endif // DATABASEMANAGER_H